package com.aya.transaction.service;

import com.aya.transaction.mapper.BlogMapper;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class BlogRequiredTransactionService {
    @Resource
    BlogSimpleTransactionService blogSimpleTransactionService;

    @Transactional
    public void updateByIdSuccess(String id, String content, String id2, String content2) {
        blogSimpleTransactionService.updateById(id, content);
        blogSimpleTransactionService.updateById(id2, content2);
    }

    @Transactional
    public void updateByIdInnerFailure(String id, String content, String id2, String content2) {
        blogSimpleTransactionService.updateById(id, content);
        blogSimpleTransactionService.updateByIdRequiredFail(id2, content2);
    }

    /**
     * 当 事物2 失败,  会回滚事物1 的内容
     */
    @Transactional
    public void updateByIdCatchFailure(String id, String content, String id2, String content2) {
        blogSimpleTransactionService.updateById(id, content);
        try {
            blogSimpleTransactionService.updateByIdRequiredFail(id2, content2);
        } catch (DuplicateKeyException e) {
            e.printStackTrace();
        }
    }
@Resource
    BlogMapper blogMapper;
    @Transactional
    public void updateByDuplicate(String id, String content, String id2, String content2) {
        blogMapper.updateById(id, content);
        try {
            blogMapper.insertBlog(id2, content2);
        } catch (DuplicateKeyException e) {
            System.out.println("duplicate ignore");
        }
    }

    @Transactional
    public void updateByIdOuterFailure(String id, String content, String id2, String content2) {
        blogSimpleTransactionService.updateById(id, content);
        blogSimpleTransactionService.updateById(id2, content2);
        throw new RuntimeException("exception");
    }

}
